package com.acane.instagram.feature.chat

import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.Notification
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.viewmodel.ChatViewModel
import kotlinx.coroutines.launch


@Composable
fun ChatRoute(
    chatViewModel: ChatViewModel,
    navController: NavHostController,
    toProfile: (String) -> Unit,
) {
    // homeViewModel.currentUserInfo?.userName?.let {
    SessionManager.currentUser?.userName?.let {
        ChatScreen(
            viewModel = chatViewModel,
            sender = it,
            navController = navController,
            toProfile = toProfile,
        )
    }
    //}
}


@SuppressLint("StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun ChatScreen(
    viewModel: ChatViewModel,
    sender: String,
    navController: NavHostController,
    toProfile: (String) -> Unit,
) {

    val courtingScope = rememberCoroutineScope()


    var messageText by remember { mutableStateOf("") }
    val receiver = viewModel.chatName
    val userInfo = viewModel.receiver


    val context = LocalContext.current

    val messages by viewModel.messages.collectAsState() // 观察 StateFlow

    val filePickerLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.OpenMultipleDocuments()
    ) { uris ->
        if (uris.isNotEmpty()) {
            uris.forEach { uri ->
                courtingScope.launch {
                    // 先执行发送操作（等待完成）
                    viewModel.sendMediaMessage(
                        toName = receiver,
                        fileUri = uri,
                        fromName = sender,
                        context = context
                    )
                }
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White
                ),
                navigationIcon = {
                    Row(
                        modifier = Modifier.padding(end = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        androidx.wear.compose.material3.IconButton(
                            onClick = {
                                navController.popBackStack()
                            },
                            modifier = Modifier
                                .size(45.dp)
                                .padding(start = 10.dp, end = 10.dp)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.arrow_left),
                                contentDescription = "back",
                                modifier = Modifier
                                    .size(30.dp)
                            )
                        }
                        Spacer(modifier = Modifier.width(10.dp))
                        AsyncImage(
                            model = userInfo.avatar?.let {
                                val url = "${Config.ADDRESS}avatars/$it"
                                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                url
                            },
                            contentScale = ContentScale.Crop,
                            contentDescription = "用户头像",
                            modifier = Modifier
                                .size(30.dp)
                                .clip(CircleShape)
                                .clickableNoRipple {
                                    toProfile(userInfo.id!!)
                                },
                            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                        )
                        Column(
                        ) {
                            userInfo.nickName?.let {
                                Text(
                                    text = it,
                                    fontWeight = FontWeight.Bold,
                                    fontSize = 14.sp,
                                    modifier = Modifier.padding(top = 15.dp, start = 10.dp)
                                )
                            }
                            userInfo.userName?.let {
                                Text(
                                    text = it,
                                    fontSize = 12.sp,
                                    modifier = Modifier.padding(start = 10.dp),
                                    color = InstagramDarkGray
                                )
                            }
                        }


                    }
                },
            )
        },
        containerColor = Color.White
    ) { paddingValues ->

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .imePadding() // 添加 imePadding 以处理软键盘
        ) {
            LazyColumn(
                //state = listState,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .padding(16.dp),
                reverseLayout = true
            ) {
                Log.d("Chat", "🟢 聊天记录：\n${viewModel.messages.value}")
                items(messages) { message ->
                    ChatBubble(
                        message = message,
                        isOwnMessage = message.sender == sender,
                        receiver = userInfo
                    )
                }
            }
            ChatInput(
                value = messageText,
                onValueChange = { messageText = it },
                onSendClick = {
                    if (messageText.isNotBlank()) {
                        viewModel.sendMessage(
                            toName = receiver,
                            message = messageText,
                            fromName = sender,
                            context = context
                        )
                        //viewModel.loadChatHistory(sender, receiver)
                        //Log.d("ChatRoute", "🟢 当前聊天记录：${viewModel.messages.value}")
                        messageText = ""

                    }
                },
                onShowMediaSheet = {
                    filePickerLauncher.launch(arrayOf("image/*", "video/*")) // 同时支持图片和视频
                }
            )
        }
    }
}

@Composable
private fun ChatBubble(
    message: Notification.ChatMessage,
    isOwnMessage: Boolean,
    modifier: Modifier = Modifier,
    receiver: UserInfo,
) {
    Box(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        contentAlignment = if (isOwnMessage)
            Alignment.CenterEnd else Alignment.CenterStart
    ) {

        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            if (!isOwnMessage) {
                AsyncImage(
                    model = receiver.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    },
                    contentScale = ContentScale.Crop,
                    contentDescription = "用户头像",
                    modifier = Modifier
                        .size(30.dp)
                        .clip(CircleShape),
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
            }

            val content = message.content ?: "Empty message" // 提供默认值
            if (message.mediaType == "text") {
                Surface(
                    color = if (isOwnMessage)
                        MaterialTheme.colorScheme.primary
                    else
                        InstagramLightGray,
                    shape = MaterialTheme.shapes.medium,
                    modifier = Modifier.padding(horizontal = 8.dp)
                ) {
                    Text(
                        text = content,
                        modifier = Modifier.padding(8.dp),
                        color = if (isOwnMessage)
                            MaterialTheme.colorScheme.onPrimary
                        else
                            Color.Black
                    )
                }
            } else if (message.mediaType == "video") {
                VideoPlayerWithThumbnail(message.content)
            } else if (message.mediaType == "image") {
                AsyncImage(
                    model = message.content.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("MeRoute", "🟢 尝试加载图片消息 URL: $url")
                        url
                    },
                    contentScale = ContentScale.Crop,
                    contentDescription = "图片消息",
                    modifier = Modifier
                        .size(100.dp),
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChatInput(
    value: String,
    onValueChange: (String) -> Unit,
    onSendClick: () -> Unit,
    onShowMediaSheet: () -> Unit, // 添加此参数
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Surface(
            color = InstagramLightGray,
            shape = MaterialTheme.shapes.medium,
            //modifier = Modifier.padding(horizontal = 8.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                TextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier.weight(1f),
                    placeholder = { Text("发消息...") },
                    colors = TextFieldDefaults.textFieldColors(
                        backgroundColor = Color.Transparent, // 设置背景颜色为透明
                        focusedIndicatorColor = Color.Transparent, // 移除焦点指示器
                        unfocusedIndicatorColor = Color.Transparent // 移除未焦点指示器
                    )
                )
                Spacer(modifier = Modifier.weight(1f))
                if (value.isBlank()) {
                    // 语音消息
                    IconButton(
                        onClick = {}
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.audio),
                            contentDescription = "audio",
                            modifier = Modifier.size(25.dp)
                        )
                    }
                    // 图片信息
                    IconButton(
                        onClick = {
                            onShowMediaSheet()
                        }
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.photo),
                            contentDescription = "photo",
                            modifier = Modifier.size(25.dp)
                        )
                    }
                } else {
                    Text(
                        text = "发送",
                        color = InstagramBlue,
                        modifier = Modifier
                            .padding(end = 10.dp)
                            .clickableNoRipple {
                                onSendClick()
                            }
                    )
                }
            }
        }

    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    // ChatRoute()
}
